class EventTarget {
  constructor() {
    Object.defineProperty(this, 'listeners', {
      value: {}
    })
  }
  on(type, callback) {
    if (!(type in this.listeners)) {
      this.listeners[type] = [];
    }
    this.listeners[type].push(callback);
  }
  off(type, callback) {
    if (!(type in this.listeners)) {
      return;
    }
    let stack = this.listeners[type];
    for (let i = 0, l = stack.length; i < l; i++) {
      if (stack[i] === callback) {
        stack.splice(i, 1);
        return this.removeEventListener(type, callback);
      }
    }
  }
  emit(event) {
    if (!(event.type in this.listeners)) {
      return;
    }
    let stack = this.listeners[event.type];
    event.target = this;
    for (let i = 0, l = stack.length; i < l; i++) {
      stack[i].call(this, event);
    }
  }
  dispatchEvent(event){
    return this.emit(event)
  }
  addEventListener(type, callback){
    return this.on(type, callback)
  }
  removeEventListener(type, callback) {
    return this.off(type, callback)
  }
}

export default EventTarget